import React from 'react';
import {
  Form,
  Input,
  Tooltip,
  Icon,
  Cascader,
  Select,
  Row,
  Col,
  Checkbox,
  Button,
  AutoComplete,
  Radio,
  message
} from 'antd';
import styles from './index.less'
import { connect } from 'dva'
import router from 'umi/router'
const { Option } = Select;
const { Group } = Radio;
const creator = (type, payload) => ({ type, payload })

const stage = ['小学', '初中', '高中', '大学', '考研', '硕士', '博士', '博士后', '职场', '创业']
const sex = ['男', '女', '保密']

// @Form.create()
// @connect()
class RegistrationForm extends React.Component {
  state = {
    confirmDirty: false,
    autoCompleteResult: [],
    visible:false,
  };

  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {//表单验证通过
        const {username,password,sex,lifestage,email,code}=values;
        let payload={
          username,
          password,
          sex,
          lifestage,
          email,
          code
        }
        this.props.dispatch(creator('users/register',payload));
      }
    });
  };

  handleConfirmBlur = e => {
    const { value } = e.target;
    this.setState({ confirmDirty: this.state.confirmDirty || !!value });
  };

  compareToFirstPassword = (rule, value, callback) => {
    const { form } = this.props;
    if (value && value !== form.getFieldValue('password')) {
      callback('两次密码不一致!');
    } else {
      callback();
    }
  };
  validateEmail=(rule,value,callback)=>{

    if(value){
      let reg=/^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/;
      let flag=reg.test(value)
      if(flag){
        this.setState({
          visible:true
        })
        callback()
      }else{
        callback('邮箱格式有误，请重新输入！')
      }
    }
    callback()
  }
  validateToNextPassword = (rule, value, callback) => {
    const { form } = this.props;
    if (value && this.state.confirmDirty) {
      form.validateFields(['confirm'], { force: true });
    }
    callback();
  };
  //获取验证码
  getCode=()=>{
    //code为0表示获取验证码
    const {dispatch,form}=this.props;
    const email=form.getFieldValue('email')
    dispatch(creator('users/register',{email,code:'0'})).then(res=>{
      if(res.httpStatus===200){
        message.success('验证码已发送，请注意查收！')
      }
    })
  }
  render() {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 },
      },
    };
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 24,
          offset: 0,
        },
        sm: {
          span: 16,
          offset: 8,
        },
      },
    };

    return (
      <div className={styles.layout}>
        <Form {...formItemLayout} onSubmit={this.handleSubmit} className={styles.register_form}>

          <div className={styles.logo}></div>
          <Form.Item label="用户名">
            {getFieldDecorator('username', {
              rules: [
                {
                  required: true,
                  message: '请输入用户名!',
                },
              ],
            })(<Input />)}
          </Form.Item>
          <Form.Item label="性别">
            {getFieldDecorator('sex', {
              rules: [
                {
                  required: true,
                  message: '请选择一项!',
                },
              ],
            })(<Group>
              {sex.map(item =>
                <Radio key={item} value={item}>
                  {item}
                </Radio>
              )}
            </Group>)}
          </Form.Item>
          <Form.Item label="所处阶段">
            {getFieldDecorator('lifestage', {
              rules: [
                {
                  required: true,
                  message: '请选择一项!',
                },
              ],
            })(<Select >
              {stage.map(item =>
                <Option key={item}>
                  {item}
                </Option>
              )}
            </Select>)}
          </Form.Item>
          <Form.Item label="密码" hasFeedback>
            {getFieldDecorator('password', {
              rules: [
                {
                  required: true,
                  message: '请输入密码!',
                },
                {
                  validator: this.validateToNextPassword,
                },
              ],
            })(<Input.Password />)}
          </Form.Item>
          <Form.Item label="确认密码" hasFeedback>
            {getFieldDecorator('confirm', {
              rules: [
                {
                  required: true,
                  message: '请再次输入密码!',
                },
                {
                  validator: this.compareToFirstPassword,
                },
              ],
            })(<Input.Password onBlur={this.handleConfirmBlur} />)}
          </Form.Item>
          <Form.Item label="邮箱地址">
            {getFieldDecorator('email', {
              validateTrigger:"onBlur",
              rules: [
                {
                  required: true,
                  message: '请输入邮箱地址!',
                },
                {
                  validator: this.validateEmail,
                },
              ],
            })(<Input />)}
          </Form.Item>
          <Form.Item label="验证码" style={{display:this.state.visible?'block':'none'}}>
            {getFieldDecorator('code', {
              
              rules: [
                {
                  required: true,
                  message: '请输入邮箱验证码!',
                },
              ],
            })(
              <div>
              <Input style={{width:'70%',marginRight:10}}/><Button type='primary' onClick={this.getCode}>获取邮箱验证码</Button>
              </div>
            )}
          </Form.Item>
          <Form.Item {...tailFormItemLayout}>
            {getFieldDecorator('agreement', {
              valuePropName: 'checked',
              rules: [{ required: true, message: '请勾选智者协议' }]
            })(
              <Checkbox>
                本人已知晓 <a href="">智者协议</a>
              </Checkbox>,
            )}
          </Form.Item>
          <Form.Item wrapperCol={{ span: 24 }}>
            <Button type="primary" htmlType="submit" className={styles.register_form_button }>
              注册
            </Button>
          </Form.Item>
          <Form.Item wrapperCol={{ span: 24 }}>
            已注册，点击 <Button type="primary" onClick={()=>{router.push('/users/login')}}>登入</Button>
          </Form.Item>
        </Form>
      </div>
    );
  }
}
// export default RegistrationForm
const WrappedRegistrationForm = Form.create({ name: 'register' })(RegistrationForm);

export default connect(({users})=>({users}))(WrappedRegistrationForm);

